import Vue from "vue";
import VueRouter from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { constantRoutes } from "./home.js"; // 静态路由

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  base:"/admin/",
  routes: constantRoutes //初始化加入静态路由
});

//全局路由守卫
router.beforeEach((to, from, next) => {
  console.log(to,from)
  //验证是否登录,目标页面是登录页除外
  if(sessionStorage.getItem("token") || to.name == 'login' || to.name == '405'){
    if (to.path !== from.path) {
      NProgress.start();
    }
    //验证路由权限
  if( !to.meta.isTab  || to.name == 'login' || sessionStorage.getItem("auth").indexOf(to.name)>-1){
      next()
    }else{
      //没有权限跳转405页面
      next({path:'405'})
    }
  }else{
    //未登录，跳转登录页
    next({path:'login'})
  }
  
});

router.afterEach(() => {
  NProgress.done();
});

//解决路由重复点击报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

export default router;
